﻿using Device.Domain;
using Device.Infrstructre.Impl;
using Device.Infrstructre.Interface;
using Device.Read.API.Applcation.Command.UnitCommand;
using MediatR;

namespace Device.Read.API.Applcation.CommandHandlers.UnitCommandHandlers
{
    /// <summary>
    /// 单位显示
    /// </summary>
    public class SelectUnitCommandHandlers : IRequestHandler<SelectUnitCommand, Unitpage<UnitModel>>
    {
        private readonly IUnitRepository _unitRepository;
        public SelectUnitCommandHandlers(IUnitRepository unitRepository)
        {
            this._unitRepository = unitRepository;
        }

        public async Task<Unitpage<UnitModel>> Handle(SelectUnitCommand request, CancellationToken cancellationToken)
        {
            Unitpage<UnitModel> page = new Unitpage<UnitModel>();
            var list = (await _unitRepository.GetAllAsync()).Where(x => x.Office_Id == request.Office_Id && x.User_Id == request.User_Id && x.IsDel == false);
            //单位名称模糊查询
                if (!string.IsNullOrEmpty(request.UnitName))
            {
                list = list.Where(t => t.UnitName == request.UnitName).ToList();
            }
            //单位编号查询
            if (!string.IsNullOrEmpty(request.UnitCode))
            {
                list = list.Where(t => t.UnitCode == request.UnitCode).ToList();
            }
            page.listcount = list.Count();
            page.pagecount = (int)Math.Ceiling(page.listcount * 1.0 / request.pagesize);
            page.list = list.OrderByDescending(t=>t.UnitId).Skip((request.pageindex - 1) * request.pagesize).Take(request.pagesize).ToList();
            return page;
        }
    }
}
